import React, {Suspense, useEffect} from 'react'
import {useDispatch, useSelector} from "react-redux";
import SysErrorBoundary from "@/components/SysErrorBoundary";
import zhCN from "antd/locale/zh_CN";
import {ConfigProvider, theme} from "antd";
import {getDarkMode, setDarkMode} from "@/store/modules/theme/themeSlice.ts";
import AuthRouter from "@/components/RouterUtil/AuthRouter.tsx";
import {FiveDotLoading} from "@/components/Loading";
import OtherOP from "@/components/OpComponent";

function App() {
    const {antdTheme} = useTheme()

    return <>
        <SysErrorBoundary>
            <ConfigProvider locale={zhCN}
                            componentSize={'middle'}
                            theme={antdTheme}>
                <Suspense fallback={<FiveDotLoading/>}>
                    <OtherOP>
                        <AuthRouter></AuthRouter>
                    </OtherOP>
                </Suspense>
            </ConfigProvider>
        </SysErrorBoundary>
    </>
}


function useTheme() {
    const {defaultAlgorithm, darkAlgorithm} = theme;
    const dispatch = useDispatch()
    const darkMode = useSelector(getDarkMode);
    const settings = useSelector((state: any) => state.theme.settings)

    const prefers = window.matchMedia('(prefers-color-scheme: dark)');

    const changeMatches = (e: any) => {
        if (e.matches) {
            dispatch(setDarkMode(true))
            document.documentElement.setAttribute('data-theme', 'dark')
        } else {
            dispatch(setDarkMode(false))
            document.documentElement.setAttribute('data-theme', 'light')
        }
    }
    useEffect(() => {
        if (settings.themeScheme === 'auto') {
            prefers.addEventListener('change', changeMatches)
            return () => {
                prefers.removeEventListener('change', changeMatches)
            }
        } else {
            document.documentElement.setAttribute('data-theme', settings.themeScheme)
        }
    }, [settings.themeScheme]);


    return {
        antdTheme: {
            algorithm: darkMode ? darkAlgorithm : defaultAlgorithm,
            token: {
                colorPrimary: '#9254de',
            },
            components: {
                Menu: {
                    /* 这里是你的组件 token */
                    // 收起后的宽度
                    collapsedWidth: 58,
                },
            },
        }
    }
}

export default App
